package org.opens.netty.chatServer.server.session.impl;

import io.netty.channel.Channel;
import org.opens.netty.chatServer.server.session.Group;
import org.opens.netty.chatServer.server.session.GroupSession;
import org.opens.netty.chatServer.server.session.SessionFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class GroupSessionMemoryImpl implements GroupSession {

    private static Map<String, Group> groupMap = new ConcurrentHashMap<>();

    @Override
    public Group createGroup(String name, Set<String> members) {
        Group group = groupMap.get(name);
        if (group != null) {
            return group;
        }

        groupMap.put(name, new Group(name, members));

        // 返回null表示group是新建的
        return null;
    }

    @Override
    public Group joinMember(String name, String member) {
        Group group = groupMap.get(name);
        if (group == null) {
            return null;
        }
        group.getMembers().add(name);
        return group;
    }

    @Override
    public Group removeMember(String name, String member) {
        Group group = groupMap.get(name);
        if (group == null) {
            return null;
        }
        group.getMembers().remove(name);
        return group;
    }

    @Override
    public Group removeGroup(String name) {
        Group group = groupMap.get(name);
        if (group == null) {
            return null;
        }
        groupMap.remove(name);
        return group;
    }

    @Override
    public Set<String> getMembers(String name) {
        Group group = groupMap.get(name);
        if (group == null) {
            return Collections.EMPTY_SET;
        }
        return group.getMembers();
    }

    @Override
    public List<Channel> getMembersChannel(String name) {
        return getMembers(name).stream().map(item -> SessionFactory.getSession().getChannel(item))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
